package com.woodws.document.util;

import com.woodws.document.interceptor.ExpInterceptor;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

/**
 * Created by maoxiaodong on 2016/11/2.
 */
public class ExcelUtil {
    public static boolean isExcel(String view) {
        return view.endsWith(".xls") || view.endsWith(".xlsx");
    }

    public static void render(HttpServletRequest request, HttpServletResponse response, ModelAndView modelAndView) {
        try {
            String view = modelAndView.getViewName();
            response.setContentType("application/octet-stream;charset=UTF-8");
            int index = view.lastIndexOf("/");
            String fileName = view.substring(index + 1, view.length());
            String contentDisposition = String.format("attachment;fileName=\"%s\"", fileName);
            String userAgent = request.getHeader("User-Agent");
            if (userAgent != null) {
                userAgent = userAgent.toLowerCase();
                if (userAgent.indexOf("firefox") != -1) {
                    contentDisposition = String.format("attachment;fileName*=UTF-8''%s", fileName);
                }
            }
            response.setHeader("Content-Disposition", contentDisposition);
            String templates = view;
            InputStream is = ExpInterceptor.class.getResourceAsStream(templates);
            OutputStream os = response.getOutputStream();
            Map<String, Object> map = modelAndView.getModel();
            Context context = new Context(map);
            JxlsHelper.getInstance().processTemplate(is, os, context);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
